// 显示注册表单
document.getElementById('showRegisterLink').addEventListener('click', function() {
    document.getElementById('loginSection').style.display = 'none';
    document.getElementById('registrationSection').style.display = 'block';
});

// 显示登录表单
document.getElementById('showLoginLink').addEventListener('click', function() {
    document.getElementById('registrationSection').style.display = 'none';
    document.getElementById('loginSection').style.display = 'block';
});

// 显示消息
function displayMessage(msg) {
    const messageElement = document.getElementById('message');
    messageElement.innerText = msg;
    setTimeout(() => {
        messageElement.innerText = '';
    }, 3000); // 3秒后清除消息
}

// 处理注册表单提交
document.getElementById('registrationForm').addEventListener('submit', function(event) {
    event.preventDefault();

    // 检查输入字段是否包含空格
    const name = document.getElementById('name').value.trim();
    const email = document.getElementById('email').value.trim();
    const contactInfo = document.getElementById('contactInfo').value.trim();
    const password = document.getElementById('password').value.trim();
    const address = document.getElementById('address').value.trim();

    if (name.includes(' ') || email.includes(' ') || contactInfo.includes(' ') || password.includes(' ') || address.includes(' ')) {
        displayMessage('注册信息中不能包含空格。');
        return; // 阻止表单提交
    }

    const userData = {
        name: name,
        email: email,
        contactInfo: contactInfo,
        password: password,
        address: address
    };

    fetch('/api/users', { // 确保端点 URL 正确
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(userData)
    })
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.json();
        })
        .then(data => {
            displayMessage('注册成功！请登录。');
            document.getElementById('registrationForm').reset();
            document.getElementById('registrationSection').style.display = 'none';
            document.getElementById('loginSection').style.display = 'block';
        })
        .catch(error => {
            displayMessage('注册失败，请重试。');
            console.error('Error:', error);
        });
});

// 处理登录表单提交
document.getElementById('loginForm').addEventListener('submit', function(event) {
    event.preventDefault();

    const loginData = {
        email: document.getElementById('loginEmail').value,
        password: document.getElementById('loginPassword').value
    };

    fetch('/api/users/login', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(loginData)
    })
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.json();
        })
        .then(data => {
            if (data && data.userId) {
                displayMessage('登录成功！');
                console.log('登录人信息：', data); // 输出登录人信息到控制台

                // 设置Cookie来存储用户ID
                document.cookie = `user_id=${data.userId}; path=/; secure; HttpOnly; SameSite=Strict`;

                // 重定向到个人中心页面
                window.location.href = 'page1.htm';
            } else {
                displayMessage('登录失败，用户名或密码错误。');
            }
        })
        .catch(error => {
            displayMessage('登录失败，请重试。');
            console.error('Error:', error);
        });
});
